﻿using System.Transactions;
using NUnit.Framework;
using SportsStore.Builder;
using SportsStore.Repository.Repositories;
using System.Configuration;
using SportsStore.Model;
using System.Collections.Generic;
using System.Linq;

namespace SportsStore.IntegrationTests.Repositories
{
  [TestFixture]
  public class ProductRepositoryTest
  {
    private Product _product;
    private TransactionScope _transactionScope;
    private ProductRepository _productRepository;

    [SetUp]
    public void Setup()
    {
      _transactionScope = new TransactionScope();

      _productRepository = new ProductRepository(ConfigurationManager.ConnectionStrings["SportsStore"].ConnectionString);

      _product = BuildMeA
        .Product("name1", "description1", 100M);

      _productRepository.Create(_product);
    }

    [TearDown]
    public void TearDown()
    {
      _transactionScope.Dispose();
    }

    [Test]
    public void WhenIAddProductsToTheDatabase_ThenICanRetrieveTheFirstPage()
    {
      PagedResult<Product> retrievedProduct = _productRepository.GetProducts(1, 4, null);
      Assert.That(retrievedProduct.ItemsPerPage, Is.EqualTo(4));
    }

    [Test]
    public void WhenIAddProductsToTheDatabase_ThenICanRetrieveTheSecondPage()
    {
      PagedResult<Product> retrievedProduct = _productRepository.GetProducts(2, 2, null);
      Assert.That(retrievedProduct.ItemsPerPage, Is.EqualTo(2));
    }

    [Test]
    public void GivenThereAreProductsForMultipleCategories_WhenIGetAllProductsForThatCategory_ThenIGetTheCorrectProducts
      ()
    {
      var retrievedProducts = _productRepository.GetProducts(1, 3, "Soccer");

      Assert.That(retrievedProducts.Results.Count, Is.EqualTo(3));
    }

    [Test]
    public void
      GivenThereAreProductsForMultipleCategories_WhenIGetAllProductsForThatCategory_ThenIGetTheCorrectNumberOfPages()
    {
      var retriedvedProducts = _productRepository.GetProducts(1, 3, "Chess");

      Assert.That(retriedvedProducts.TotalPages, Is.EqualTo(2));
    }

    [Test]
    public void GivenAProductId_WhenIAskForTheProduct_IGetTheCorrectProduct()
    {
      Product product = _productRepository.GetProduct(_product.Id);

      Assert.That(product, Is.Not.Null);
      Assert.That(product.Id, Is.EqualTo(_product.Id));
    }
  }
}
